package io.cloud.tec.project.util;

import io.cloud.tec.project.enums.RsaKeyType;
import org.apache.commons.codec.binary.StringUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RsaUtil {

    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    //获得公钥字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) {
        //获得map中的公钥对象 转为key对象
        Key key = (Key) keyMap.get(RsaKeyType.RSAPublicKey.name());
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }


    //获得私钥字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
        //获得map中的私钥对象 转为key对象
        Key key = (Key) keyMap.get(RsaKeyType.RSAPrivateKey.name());
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }

    //获取公钥
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = decryptBASE64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    //获取私钥
    public static PrivateKey getPrivateKey(String key) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = decryptBASE64(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    //解码返回byte
    public static byte[] decryptBASE64(String key) throws IOException {
        return java.util.Base64.getDecoder().decode(key);
//        return Base64.decodeBase64(key);
    }


    //编码返回字符串
    public static String encryptBASE64(byte[] key) {
        return StringUtils.newStringIso8859_1(java.util.Base64.getEncoder().encode(key));
//        return Base64.encodeBase64String(key);
    }

    //***************************签名和验证*******************************
    public static byte[] sign(byte[] data, String privateKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        PrivateKey priK = getPrivateKey(privateKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(priK);
        sig.update(data);
        return sig.sign();
    }

    public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
        PublicKey pubK = getPublicKey(publicKeyStr);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(pubK);
        sig.update(data);
        return sig.verify(sign);
    }

    //************************加密解密**************************
    public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = plainText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            cache = cipher.doFinal(plainText, offSet, Math.min(inputLen - offSet, MAX_ENCRYPT_BLOCK));
            out.write(cache, 0, cache.length);
            offSet += MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptText = out.toByteArray();
        out.close();
        return encryptText;
    }

    public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        int inputLen = encryptText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            cache = cipher.doFinal(encryptText, offSet, Math.min(inputLen - offSet, MAX_DECRYPT_BLOCK));
            out.write(cache, 0, cache.length);
            offSet += MAX_DECRYPT_BLOCK;
        }
        byte[] plainText = out.toByteArray();
        out.close();
        return plainText;
    }


    public static void main(String[] args) {
        Map<String, Object> keyMap;
        byte[] cipherText;
        String input = "Hello World!";
        try {
            keyMap = initKey();
            String publicKey = getPublicKeyStr(keyMap);
            System.out.println("公钥------------------");
            System.out.println("-----BEGIN PUBLIC KEY-----");
            System.out.println(publicKey);
            System.out.println("-----END PUBLIC KEY-----");

            String privateKey = getPrivateKeyStr(keyMap);
            System.out.println("私钥------------------");
            System.out.println("-----BEGIN PRIVATE KEY-----");
            System.out.println(privateKey);
            System.out.println("-----END PRIVATE KEY-----");

            System.out.println("测试可行性-------------------");
            System.out.println("明文=======" + input);

            cipherText = encrypt(input.getBytes(), publicKey);
            //加密后的东西
            System.out.println("密文=======" + encryptBASE64(cipherText));
            //开始解密
            byte[] plainText = decrypt(cipherText, privateKey);
            System.out.println("解密后明文===== " + new String(plainText));

            System.out.println("\n验证签名-----------");
            String str = "被签名的内容";
            System.out.println("原文:" + str);
            byte[] signature = sign(str.getBytes(), privateKey);
            boolean status = verify(str.getBytes(), signature, publicKey);
            System.out.println("验证情况：" + status);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void mmapWriteFile(String fileKey, RsaKeyType keyType, String key) throws IOException {
        String file = RsaKeyType.RSAPublicKey == keyType ? fileKey + keyType + ".pub" :
                RsaKeyType.RSAPrivateKey == keyType ? fileKey + keyType : fileKey;
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        String begin = RsaKeyType.RSAPublicKey == keyType ? "-----BEGIN PUBLIC KEY-----\n" :
                RsaKeyType.RSAPrivateKey == keyType ? "-----BEGIN PRIVATE KEY-----\n" : "";
        String end = RsaKeyType.RSAPublicKey == keyType ? "-----END PUBLIC KEY-----\n" :
                RsaKeyType.RSAPrivateKey == keyType ? "-----END PRIVATE KEY-----\n" : "";

        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, begin.length() + key.length() + end.length());
        mappedByteBuffer.put(begin.getBytes(StandardCharsets.UTF_8));
        mappedByteBuffer.put(key.getBytes(StandardCharsets.UTF_8));
        mappedByteBuffer.put(end.getBytes(StandardCharsets.UTF_8));

        fileChannel.close();
        randomAccessFile.close();
    }

    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
        //实例化密钥生成器
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        //初始化密钥生成器
        //密钥长度，DH算法的默认密钥长度是1024
        //密钥长度必须是64的倍数，在512到65536位之间
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(RsaKeyType.RSAPublicKey.name(), publicKey);
        keyMap.put(RsaKeyType.RSAPrivateKey.name(), privateKey);
        return keyMap;
    }
}
